﻿using System;
using System.Net.Http;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using BookSourceVerification.exception;
using BookSourceVerification.execute;
using BookSourceVerification.service;
using BookSourceVerification.service.impl;
using Microsoft.Win32;
using NLog;
using NLog.Targets;

namespace BookSourceVerification
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private readonly VerifyBookSourceExecute _verifyBookSourceExecute = new(new CheckSourceHttpServiceImpl());
        private static readonly Logger Logger = LogManager.GetCurrentClassLogger();


        public MainWindow()
        {
            InitializeComponent();
            SelectTextBox.Text = App.FilePath ?? "请选择文件";
            _verifyBookSourceExecute.ShowCountEvent += ResultTextBlockShowCount;
        }

        private void ResultTextBlockShowCount(int success, int check, int count, long time)
        {
            Dispatcher.Invoke(() =>
            {
                ResultTextBlock.Text = $"可用书源数：{success}，已验证书源：{check} \n " +
                                       $"书源总数：{count}，耗时：{time / 1000}秒";
            });
        }

        private void SelectFileButton_OnClick(object sender, RoutedEventArgs e)
        {
            var openFileDialog = new OpenFileDialog
            {
                Filter = "文本文件 (*.txt;*.json)|*.txt;*.json"
            };
            if (openFileDialog.ShowDialog() == true)
            {
                SelectTextBox.Text = openFileDialog.FileName;
            }
        }

        /// <summary>
        /// 拿到path路径，然后验证书源
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <exception cref="Exception"></exception>
        private async void VerifyButton_OnClick(object sender, RoutedEventArgs e)
        {
            VerifyButton.IsEnabled = false;
            LogCheckBox.IsEnabled = false;
            TestCheckBox.IsEnabled = false;
            try
            {
                // await _verifyBookSourceExecute.VerifyBookSourceEx(SelectTextBox.Text);
                var (count, successCount, elapsedMilliseconds) =
                    await _verifyBookSourceExecute.VerifyBookSource(SelectTextBox.Text);
                ResultTextBlock.Text = $"完成验证！可用书源数：{successCount} \n " +
                                       $"书源总数：{count}，耗时：{elapsedMilliseconds / 1000}秒";
            }
            catch (WarringException exception)
            {
                Logger.Error($"【可容许错误】：{exception}");
            }
            catch (Exception exception)
            {
                Logger.Error($"【界面错误】：{exception}");
            }

            VerifyButton.IsEnabled = true;
            LogCheckBox.IsEnabled = true;
            TestCheckBox.IsEnabled = true;
        }

        private void SelectTextBox_OnDrop(object sender, DragEventArgs e)
        {
            var textBox = (sender as TextBox)!;
            textBox.Text =
                (e.Data.GetData(DataFormats.FileDrop) as Array)?.GetValue(0)?.ToString() ?? "请重新拖入文件";
        }

        private void SelectTextBox_OnPreviewDragOver(object sender, DragEventArgs e)
        {
            e.Effects = DragDropEffects.Link;
            e.Handled = true;
            SelectTextBox.Cursor = Cursors.Arrow;
        }

        private void MainWindow_OnDrop(object sender, DragEventArgs e)
        {
            SelectTextBox.Text = (e.Data.GetData(DataFormats.FileDrop) as Array)?.GetValue(0)?.ToString() ?? "请重新拖入文件";
        }

        private void MainWindow_OnPreviewDragEnter(object sender, DragEventArgs e)
        {
            e.Effects = DragDropEffects.Copy;
            e.Handled = true;
            (sender as MainWindow)!.Cursor = Cursors.Arrow;
        }


        private void SelectTextBox_OnTextChanged(object sender, TextChangedEventArgs e)
        {
            var textBoxText = SelectTextBox.Text;
            var index = textBoxText.LastIndexOf(@"\", StringComparison.Ordinal);
            if (-1 == index)
            {
                return;
            }

            var str = textBoxText.Substring(index + 1);
            ResultTextBlock.Text = str + "：准备就绪。";
        }

        private void LogCheckBox_OnChecked(object sender, RoutedEventArgs e)
        {
            LogManager.Setup().LoadConfiguration(builder =>
            {
                // builder.ForLogger().FilterMinLevel(LogLevel.Info).WriteToConsole();
                builder.ForLogger().FilterMinLevel(LogLevel.Error)
                    .WriteToFile(fileName: "error.txt", encoding: Encoding.UTF8, keepFileOpen: false,
                        archiveAboveSize: 1000000, maxArchiveFiles: 5, maxArchiveDays: 30,
                        lineEnding: LineEndingMode.Default);
            });
        }

        private void LogCheckBox_OnUnchecked(object sender, RoutedEventArgs e)
        {
            LogManager.Shutdown();
        }

        private void TestCheckBox_OnChecked(object sender, RoutedEventArgs e)
        {
            var checkBookSourceService = new CheckSourceHttpServiceImpl();
            _verifyBookSourceExecute.CheckBookSourceService = checkBookSourceService;
            _verifyBookSourceExecute.UrlCheckService = UrlCheckService.GetUrlCheckService(checkBookSourceService);
            TestCheckBox.Content = "Http方式测试书源";
        }

        private void TestCheckBox_OnUnchecked(object sender, RoutedEventArgs e)
        {
            var checkBookSourceService = new CheckSourcePingServiceImpl();
            _verifyBookSourceExecute.CheckBookSourceService = checkBookSourceService;
            _verifyBookSourceExecute.UrlCheckService = UrlCheckService.GetUrlCheckService(checkBookSourceService);
            TestCheckBox.Content = "Ping方式测试书源";
        }
    }
}